class_name LogLabel
extends Control
@export var msg_panel: Control
@export var label_template: Label
@export var vbox: VBoxContainer
@export var scroll: ScrollContainer
@export var auto_scroll_down: CheckButton
@export var background: ColorRect

static var instance: LogLabel

var show_mode := "all"


func _ready() -> void:
	instance = self
	#print_log(["sdasd", "asaasaasas", "玩家出生坐三打哈俗话 决赛u杀害赛风 阿苏阿苏后 十分的还哈桑标: "])

func _process(delta: float) -> void:
	if auto_scroll_down.button_pressed:
		instance.scroll.scroll_vertical = instance.vbox.size.y + 999
		#print("滑动到底部")
	pass

# 自定义一个函数来打印日志
static func print_log(msgs:Array) -> void:
	var msg = "".join(msgs)
	msg = "log: "+msg
	print(msg)
	add_new_label(msg)
	pass
static func printerr_log(msgs:Array) -> void:
	var msg = "".join(msgs)
	msg = "err: "+msg
	printerr(msg)
	add_new_label(msg)
	pass
static func print_msg(msgs:Array) -> void:
	var msg = "".join(msgs)
	msg = "msg: "+msg
	print(msg)
	add_new_label(msg)
	pass


static func add_new_label(msg: String) -> void:
	if instance == null: return
	
	#instance.vbox.remove_child(instance.empty_line)
	
	# 复制模板标签并设置文本
	var new_label = instance.label_template.duplicate() as Label
	new_label.text = msg
	if new_label.text.begins_with("err"): new_label.modulate = Color.RED
	instance.cg_show(new_label)
	instance.vbox.add_child(new_label)
	
	# 添加空行
	#instance.vbox.add_child(instance.empty_line)
	
	# 等待当前帧渲染完毕后，再更新滚动条
	# instance.call_deferred("_update_scroll_position")

# 更新滚动条到最底部
static func _update_scroll_position() -> void:
	if instance == null: return
	# 设置滚动条的位置到vbox的高度
	instance.scroll.scroll_vertical = instance.vbox.size.y + 999
	instance.scroll.queue_redraw()

static func show_msg(mode: String) -> void:
	if instance == null: return
	instance.show_mode = mode
	for child in instance.vbox.get_children():
		var label = child as Label
		instance.cg_show(label)
	pass

func cg_show(label: Label) -> void:
	match show_mode:
			"all":
				label.visible = true
			"log":
				# 这里暂时所有不为msg的都判定为log
				label.visible = !label.text.begins_with("msg")
			"msg":
				label.visible = label.text.begins_with("msg")

func _on_all_button_up() -> void:
	show_msg("all")
func _on_log_button_up() -> void:
	show_msg("log")
func _on_msg_button_up() -> void:
	show_msg("msg")


# 当隐藏msg板开关被切换时
func _on_show_msg_panel_toggled(toggled_on: bool) -> void:
	msg_panel.visible = toggled_on
	background.visible = toggled_on
	pass # Replace with function body.
